package component.global.manager
{
	import flash.display.InteractiveObject;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.utils.Dictionary;
	
	public class KeyboardMgr extends EventDispatcher
	{
		public function KeyboardMgr(target:IEventDispatcher=null)
		{
			super(target);
			_interactiveObjects = new Dictionary(true);
		}
		
		private static var _instance:KeyboardMgr
		
		public static function get Instance():KeyboardMgr{
			if(_instance == null){
				_instance = new KeyboardMgr();
			}
			return _instance;
		}
		
		/**
		 *{interactiveObject, keys, handlers}
		 */		
		private var _interactiveObjects:Dictionary;
		
		public function addKey(interactiveObject:InteractiveObject,keys:Array = null,handlers:Array = null):void{
			if(_interactiveObjects[interactiveObject] == null){
				_interactiveObjects[interactiveObject] = {interactiveObject:interactiveObject, keys:keys, handlers:handlers};
				interactiveObject.addEventListener(KeyboardEvent.KEY_DOWN, keysHandler);
			} else {
				var tempKeys:Array = _interactiveObjects[interactiveObject].keys;
				var tempHandlers:Array = _interactiveObjects[interactiveObject].handlers;
				for (var i:int = 0; i < keys.length; i++) 
				{
					var idx:int = tempKeys.indexOf(keys[i]);
					if(idx>-1)continue;
					tempKeys.push(keys[i]);
					tempHandlers.push(handlers[i]);
				}
			}
		}
		
		public function removeKey(interactiveObject:InteractiveObject,keys:Array= null):void{
			if(_interactiveObjects[interactiveObject] == null){
				throw new Error("The interactiveObject has not been added any KeyboardEvents!");
			}
			var tempKeys:Array = keys;
			var tempHandlers:Array = _interactiveObjects[interactiveObject].handlers;
			if(tempKeys == null)tempKeys = _interactiveObjects[interactiveObject].keys;
			
			while(tempKeys && tempKeys.length>0){
				for (var i:int = 0; i < tempKeys.length; i++) 
				{
					var arr:Array = _interactiveObjects[interactiveObject].keys
					var idx:int = arr.indexOf(tempKeys[i]);
					if(idx>-1){
						tempKeys.splice(i,i+1);
						tempHandlers.splice(i,i+1);
						if(tempKeys != _interactiveObjects[interactiveObject].keys)_interactiveObjects[interactiveObject].keys.splice(idx,idx+1);
						break;
					} else {
						tempKeys.splice(i,i+1);
					}
				}
			}
			if(tempHandlers.length == 0){
				interactiveObject.removeEventListener(KeyboardEvent.KEY_DOWN, keysHandler);
				delete _interactiveObjects[interactiveObject];
			}
		}
		
		private function keysHandler(e:KeyboardEvent):void{
			var obj:Object = _interactiveObjects[e.currentTarget];
			if(obj.keys == null || obj.keys.length == 0){
				obj.handlers[0](e);
			} else {
				for (var i:int = 0; i < obj.keys.length; i++) 
				{
					if(e.keyCode == obj.keys[i]){
						obj.handlers[i](e);
						break;
					}
				}
			}
		}
	}
}